// department.js
var wxCharts = require('../../common/wxcharts-min.js');
import DEPARTMENT from '../../API/DEPARTMENT';
var Zan = require('../../style/dist/index');
var app = getApp()
var columnChart = null;
var deptChart = null;
var pieChart = null;
import APIURL from '../../const/APIURL'
Page(Object.assign({}, Zan.Tab, {
  /**
   * 页面的初始数据
   */
  data: {
    showpieChart: false,
    currentdept: {},
    departments: [],
    wholeschool: {},
    showTopTips: false,
    errorMsg: '',
    percents: [],
    deptnames: [],
    chartTitle: '各学院报到率柱形图',
    isMainChartDisplay: true,
    tab: {
      list: [],
      selectedId: 1,
      scroll: true,
      height: 45
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.setNavigationBarTitle({
      title: '学院报到情况'
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.RefreshData();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.RefreshData();
    wx.stopPullDownRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {


  },
  prepareData: function () {
    var that = this;
    var d = that.data.departments;
    var deptnames = [];
    var depthavenums = [];
    var deptregnums = [];
    var deptpercent = [];
    var allhave = 0;
    var allreg = 0;
    var boy = 0;
    var girl = 0;
    var tabs = [{ id: 0, title: '全院整体情况' }];
    for (var i = 0; i < d.length; i++) {
      deptnames.push(d[i].dept_Name.substr(0, 2));
      depthavenums.push(d[i].dept_Havenum);
      deptregnums.push(d[i].dept_Regnum);
      deptpercent.push((d[i].dept_Percent * 100).toFixed(1));
      allhave += d[i].dept_Havenum;
      allreg += d[i].dept_Regnum;
      boy += d[i].dept_boynum;
      girl += d[i].dept_girlnum;
      tabs.push({
        id: d[i].dept_Id,
        title: d[i].dept_Name
      })
    }
    var wholeschool = {
      dept_Id: 0,
      dept_Name: '全院',
      dept_Regnum: allreg,
      dept_Havenum: allhave,
      dept_Percent: (allhave / allreg).toFixed(3),
      dept_boynum: boy,
      dept_girlnum: girl,
      Percent: ((allhave / allreg) * 100).toFixed(1),
    }
    var selectid = 0;
    var id = wx.getStorageSync("currentdeptid");
    console.log(id)
    if (id != undefined && id != null && id >= 0) {
      selectid = id;
    }
    wx.setStorageSync("currentdeptid", selectid)
    this.setData({
      percents: deptpercent,
      deptnames: deptnames,
      departments: d,
      wholeschool: wholeschool,
      tab: {
        list: tabs,
        selectedId: selectid,
        scroll: true,
        height: 45
      },
    });
  },
  touchHandler: function (e) {
    var that = this;
    var index = columnChart.getCurrentDataIndex(e);
    //console.log(index)

    if (index > -1 && index < that.data.departments.length && this.data.isMainChartDisplay) {
      this.setData({
        chartTitle: that.data.departments[index].dept_Name + '的详情',
        isMainChartDisplay: false
      });
      //console.log(that.data.departments[index])

      columnChart = new wxCharts({
        canvasId: 'columnCanvas',
        type: 'column',
        categories: ['实到', '应到'],
        series: [{
          name: '报到人数',
          data: [that.data.departments[index].dept_Havenum, that.data.departments[index].dept_Regnum],
          format: function (val, name) {
            return val + '人';
          }
        }
        ],
        yAxis: {
          format: function (val) {
            return val + '人';
          },
          min: that.data.departments[index].dept_Havenum - (that.data.departments[index].dept_Havenum * 0.05).toFixed(0)

        },
        xAxis: {
          fontColor: '#7cb5ec',
        },
        width: 350,
        height: 300
      });
    }
  },
  RefreshMainChart: function () {

    var that = this;

    this.setData({
      chartTitle: '各学院报到率柱形图',
      isMainChartDisplay: true
    });
    columnChart = new wxCharts({
      canvasId: 'columnCanvas',
      type: 'column',
      categories: that.data.deptnames,
      series: [{
        name: '报到率',
        data: that.data.percents
      }],
      yAxis: {
        format: function (val) {
          return val + '%';
        }
      },
      extra: {
        column: {
          width: 20,
        }
      },
      width: 300,
      height: 300
    });
  },
  RefreshDeptChart: function () {
    var d = this.getDepartment(this.data.tab.selectedId);
    console.log(d);
    var that = this;
    deptChart = new wxCharts({
      canvasId: 'deptCanvas',
      type: 'column',
      categories: ['实到', '应到'],
      series: [{
        name: '报到人数',
        data: [d.dept_Havenum, d.dept_Regnum],
        format: function (val, name) {
          return val + '人';
        }
      }
      ],
      yAxis: {
        format: function (val) {
          return val + '人';
        },
        min: d.dept_Havenum - (d.dept_Havenum * 0.05).toFixed(0)

      },
      xAxis: {
        fontColor: '#7cb5ec',
      },
      width: 350,
      height: 300
    });

    if (d.dept_boynum == 0 && d.dept_girlnum == 0) {
      that.setData({
        showpieChart: false
      })
      return;
    }
    pieChart = new wxCharts({
      animation: true,
      canvasId: 'pieCanvas',
      type: 'ring',
      title: {
        name: "男女生比例"
      },
      series: [{
        name: '男生',
        data: d.dept_boynum,
      }, {
        name: '女生',
        data: d.dept_girlnum,
      }],
      width: 350,
      height: 300,
      dataLabel: true,
      dataPointShape: true,
      disablePieStroke: true
    });
    that.setData({
      showpieChart: true
    })
  },
  RefreshData: function () {
    wx.showLoading({
      title: '加载中',
    });
    var that = this;
    that.setData({
      departments: [{}],
      havenum: 0,
      regnum: 0,
    })
    DEPARTMENT.GetDepartments().then(function (d) {
      if (d.responseResult != 1) {
        wx.showToast({
          title: d.msg,
          icon: 'loading',
          duration: 1000,
          mask: true
        })
        that.setData({
          showTopTips: true,
          errorMsg: d.msg
        })

        setTimeout(function () {
          that.setData({
            showTopTips: false,
            errorMsg: ''
          })
        }, 2000)
      }
      else {
        //console.log(d)
        that.setData({
          departments: d.data
        })
        that.prepareData();
        that.RefreshMainChart();
        that.RefreshDeptChart();
      }
      wx.showToast({
        title: "加载成功",
      })
      
    }, function (d) {
      wx.hideLoading()
    })
  },
  handleZanTabChange(e) {
    var componentId = e.componentId;
    var selectedId = e.selectedId;

    this.setData({
      [`${componentId}.selectedId`]: selectedId,
    });
    wx.setStorageSync("currentdeptid", selectedId)
    console.log(this.data.tab.selectedId)
    this.RefreshDeptChart();

  },
  changeDept: function (event) {
    console.log(event);
    var deptid = event.currentTarget.dataset.deptid
    if (!deptid) return;
    this.setData({
      [`${'tab'}.selectedId`]: deptid,
    });
    wx.setStorageSync("currentdeptid", deptid)
    this.getDepartment(deptid);
    this.RefreshDeptChart();

  },
  getDepartment: function (deptid) {
    var that = this;
    var depts = that.data.departments;
    var dept;
    if (deptid == 0) {
      dept = that.data.wholeschool;
    } else {
      for (var i = 0; i < depts.length; i++) {
        if (depts[i].dept_Id == deptid) {
          dept = depts[i]

          console.log(dept)
        }
      }

      dept.Percent = ((dept.dept_Percent) * 100).toFixed(1);
    }
    that.setData(
      {
        currentdept: dept
      }
    )

    console.log(dept)
    return dept;
  },
}))
